import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:get/get.dart';
import '../../routes/app_pages.dart';
import 'health_score_logic.dart';

class HealthScoreView extends StatefulWidget {
  const HealthScoreView({super.key});

  @override
  State<HealthScoreView> createState() => _HealthScoreViewState();
}

class _HealthScoreViewState extends State<HealthScoreView> {
  final HealthScoreLogic controller = Get.put(HealthScoreLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('清理一点通'),
        backgroundColor: controller.getScoreColor(),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.refreshHealthScore,
          ),
        ],
      ),
      body: Obx(() => _buildBody()),
    );
  }

  Widget _buildBody() {
    if (controller.isLoading.value) {
      return const Center(child: CircularProgressIndicator());
    }

    if (controller.errorMessage.value.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            const Text('获取健康评分失败', style: TextStyle(fontSize: 18)),
            const SizedBox(height: 8),
            Text(controller.errorMessage.value, textAlign: TextAlign.center),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: controller.refreshHealthScore,
              child: const Text('重新检测'),
            ),
          ],
        ),
      );
    }

    if (controller.healthScore.value == null) {
      return const Center(child: Text('暂无数据'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildOverallScore(),
          const SizedBox(height: 12),
          const MyAdFeedView(),
          const SizedBox(height: 12),
          _buildFunctionButtons(), // 新增功能按钮区域
          const SizedBox(height: 24),
          _buildScoreDetails(),
          const SizedBox(height: 24),
          _buildRecommendations(),
        ],
      ),
    );
  }

  Widget _buildOverallScore() {
    final score = controller.healthScore.value!.overallScore;
    return Card(
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            const Text(
              '综合健康评分',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            Stack(
              alignment: Alignment.center,
              children: [
                SizedBox(
                  width: 150,
                  height: 150,
                  child: CircularProgressIndicator(
                    value: score / 100,
                    strokeWidth: 12,
                    backgroundColor: Colors.grey[200],
                    valueColor: AlwaysStoppedAnimation<Color>(controller.getScoreColor()),
                  ),
                ),
                Column(
                  children: [
                    Text(
                      score.toStringAsFixed(1),
                      style: TextStyle(
                        fontSize: 32,
                        fontWeight: FontWeight.bold,
                        color: controller.getScoreColor(),
                      ),
                    ),
                    Text(
                      controller.getScoreDescription(score),
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScoreDetails() {
    final healthScore = controller.healthScore.value!;
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '详细评分',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            _buildScoreItem(
              '内存健康',
              healthScore.memory.score,
              '使用率: ${healthScore.memory.usagePercentage.toStringAsFixed(1)}%',
              Icons.memory,
            ),
            _buildScoreItem(
              '存储健康',
              healthScore.storage.score,
              '使用率: ${healthScore.storage.usagePercentage.toStringAsFixed(1)}%',
              Icons.storage,
            ),
            _buildScoreItem(
              '温度状态',
              healthScore.temperature.score,
              '${healthScore.temperature.temperature.toStringAsFixed(1)}°C - ${controller.getTemperatureStatusText(healthScore.temperature.status)}',
              Icons.thermostat,
            ),
            _buildScoreItem(
              '安全状态',
              healthScore.security.score,
              '风险等级: ${controller.getSecurityRiskText(healthScore.security.riskLevel)}',
              Icons.security,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScoreItem(String title, double score, String subtitle, IconData icon) {
    return ListTile(
      leading: Icon(icon, color: controller.getScoreColor(score)),
      title: Text(title),
      subtitle: Text(subtitle),
      trailing: Chip(
        label: Text(
          score.toStringAsFixed(1),
          style: const TextStyle(color: Colors.white),
        ),
        backgroundColor: controller.getScoreColor(score),
      ),
    );
  }

  Widget _buildRecommendations() {
    final healthScore = controller.healthScore.value!;
    final recommendations = <Widget>[];

    // 内存建议
    if (healthScore.memory.score < 70) {
      recommendations.add(_buildRecommendationItem(
        '内存使用较高',
        '建议关闭不需要的后台应用释放内存',
        Icons.memory,
      ));
    }

    // 存储建议
    if (healthScore.storage.score < 70) {
      recommendations.add(_buildRecommendationItem(
        '存储空间不足',
        '建议清理缓存和不需要的文件',
        Icons.cleaning_services,
      ));
    }

    // 温度建议
    if (healthScore.temperature.score < 70) {
      recommendations.add(_buildRecommendationItem(
        '设备温度${healthScore.temperature.status == 'high' ? '偏高' : '过高'}',
        '建议让设备休息降温，关闭高性能应用',
        Icons.ac_unit,
      ));
    }

    // 安全建议
    if (healthScore.security.score < 100) {
      recommendations.add(_buildRecommendationItem(
        '存在安全风险',
        '建议检查设备安全设置',
        Icons.security,
      ));
    }

    if (recommendations.isEmpty) {
      recommendations.add(_buildRecommendationItem(
        '设备状态良好',
        '继续保持当前使用习惯',
        Icons.check_circle,
      ));
    }

    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '优化建议',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            ...recommendations,
          ],
        ),
      ),
    );
  }

  Widget _buildRecommendationItem(String title, String description, IconData icon) {
    return ListTile(
      leading: Icon(icon, color: Colors.blue),
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.w500)),
      subtitle: Text(description),
    );
  }

  /// 构建功能按钮网格区域
  Widget _buildFunctionButtons() {
    // 严格按截图还原：
    // 1) 第一张卡片包含四个功能：垃圾清理、手机加速、安全检测、手机降温（两列布局，每个条目：图标方块+标题+副标题+红点）
    // 2) 第二张卡片单独展示“文件碎片”条目与右侧一个长条“释放内存”按钮
    return Column(
      children: [
        _buildMainFeatureCard(),
        const SizedBox(height: 12),
        _buildMemoryReleaseCard(),
      ],
    );
  }

  /// 第一张卡片：四个功能项（垃圾清理、手机加速、安全检测、手机降温）
  Widget _buildMainFeatureCard() {
    return Card(
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: _buildFeatureItem(
                    title: '垃圾清理',
                    // 副标题可变：有红点显示提醒文案，无红点显示完成文案且颜色收敛
                    subtitle: controller.showJunkDot.value ? '优化您的内存' : '手机已清理',
                    icon: Icons.delete_outline,
                    // 字体颜色：有红点使用强调色，无红点使用灰色
                    accentColor: controller.showJunkDot.value ? Colors.redAccent : Colors.grey[600],
                    onTap: () => Get.toNamed(Routes.junkCleanup),
                    // 红点：默认显示；在清理完成后由逻辑层关闭
                    showRedDot: controller.showJunkDot.value,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: _buildFeatureItem(
                    title: '手机加速',
                    // 副标题可变：有红点显示提醒文案，无红点显示完成文案且颜色收敛
                    subtitle: controller.showBoostDot.value ? '卡慢，请加速' : '运行流畅',
                    icon: Icons.speed,
                    // 字体颜色：有红点使用强调色，无红点使用灰色
                    accentColor: controller.showBoostDot.value ? Colors.deepOrange : Colors.grey[600],
                    onTap: () => Get.toNamed(Routes.phoneBoost),
                    // 红点：加速完成后关闭
                    showRedDot: controller.showBoostDot.value,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: _buildFeatureItem(
                    title: '安全检测',
                    subtitle: '远离网络劫持',
                    icon: Icons.security,
                    accentColor: Colors.grey[600],
                    onTap: () => Get.toNamed(Routes.securityScan),
                    // 红点：仅在有安全风险时显示
                    showRedDot: controller.showSecurityDot.value,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: _buildFeatureItem(
                    title: '手机降温',
                    subtitle: '缓解手机发热',
                    icon: Icons.ac_unit, // 使用内置图标，避免不可用图标编译失败
                    accentColor: Colors.grey[600],
                    onTap: () => Get.toNamed(Routes.phoneCoolDown),
                    // 红点：降温完成后关闭
                    showRedDot: controller.showCooldownDot.value,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 第二张卡片：左侧“文件碎片”条目 + 右侧一个长条的“释放内存”按钮
  Widget _buildMemoryReleaseCard() {
    return Card(
      elevation: 4,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '清理加速',
              style: TextStyle(fontSize: 14, color: Colors.grey[500]),
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                // 左侧：文件碎片条目（带红点）
                Expanded(
                  child: _buildFeatureItem(
                    title: '文件碎片',
                    subtitle: '系统专属碎片清理',
                    icon: Icons.security, // 使用稳定可用的图标
                    accentColor: Colors.black87,
                    onTap: () => Get.toNamed(Routes.memoryRelease),
                    // 红点：释放内存完成后关闭
                    showRedDot: controller.showMemoryDot.value,
                    iconBoxColor: const Color(0xFFEFF3F8), // 淡灰背景，贴近截图
                    iconColor: const Color(0xFF3A7AFE), // 蓝色图标
                  ),
                ),
                const SizedBox(width: 12),
                // 右侧：长条按钮“释放内存”
                _buildLongActionButton(
                  text: '释放内存',
                  onPressed: () => Get.toNamed(Routes.memoryRelease),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 通用的功能条目构建：图标方块 + 红点 + 标题 + 副标题
  Widget _buildFeatureItem({
    required String title,
    required String subtitle,
    required IconData icon,
    required VoidCallback onTap,
    Color? accentColor,
    bool showRedDot = true,
    Color? iconBoxColor,
    Color? iconColor,
  }) {
    final Color boxColor = iconBoxColor ?? const Color(0xFFE8F0FE); // 默认浅蓝背景
    final Color iColor = iconColor ?? const Color(0xFF3A7AFE); // 默认蓝色图标
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: Colors.white,
        ),
        child: Row(
          children: [
            // 左侧图标方块 + 红点
            Stack(
              clipBehavior: Clip.none,
              children: [
                Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: boxColor,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(icon, color: iColor),
                ),
                if (showRedDot)
                  Positioned(
                    right: -4,
                    top: -4,
                    child: Container(
                      width: 10,
                      height: 10,
                      decoration: const BoxDecoration(
                        color: Colors.red,
                        shape: BoxShape.circle,
                      ),
                    ),
                  ),
              ],
            ),
            const SizedBox(width: 12),
            // 右侧标题与副标题
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 14,
                      color: accentColor ?? Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 右侧长条按钮（“释放内存”），外观贴近截图：圆角大按钮，主色蓝色
  Widget _buildLongActionButton({
    required String text,
    required VoidCallback onPressed,
  }) {
    return ConstrainedBox(
      constraints: const BoxConstraints(minWidth: 140, minHeight: 44),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF3A7AFE),
          foregroundColor: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
        ),
        child: Text(
          text,
          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
        ),
      ),
    );
  }

  /// 构建单个功能按钮
  Widget _buildFunctionButton(
    String title,
    IconData icon,
    Color color,
    VoidCallback onPressed, {
    bool isAnimated = false,
    bool showStatus = false,
    String status = '',
    bool showTemperature = false,
    double temperature = 0.0,
    bool showProgress = false,
    double progress = 0.0,
  }) {
    return InkWell(
      onTap: onPressed,
      borderRadius: BorderRadius.circular(12),
      child: Container(
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: color.withOpacity(0.3)),
        ),
        padding: const EdgeInsets.all(12),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Stack(
              alignment: Alignment.center,
              children: [
                Icon(
                  icon,
                  size: 32,
                  color: color,
                ),
                if (isAnimated)
                  Positioned.fill(
                    child: Obx(() => controller.isBoosting.value
                        ? const CircularProgressIndicator(strokeWidth: 2)
                        : const SizedBox()),
                  ),
                if (showProgress)
                  Positioned.fill(
                    child: CircularProgressIndicator(
                      value: progress,
                      strokeWidth: 2,
                      backgroundColor: color.withOpacity(0.2),
                      valueColor: AlwaysStoppedAnimation<Color>(color),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: color,
              ),
              textAlign: TextAlign.center,
            ),
            if (showStatus && status.isNotEmpty)
              Text(
                status,
                style: TextStyle(
                  fontSize: 10,
                  color: Colors.grey[600],
                ),
              ),
            if (showTemperature)
              Text(
                '${temperature.toStringAsFixed(1)}°C',
                style: TextStyle(
                  fontSize: 10,
                  color: controller.getTemperatureColor(temperature),
                ),
              ),
            if (showProgress)
              Text(
                '${(progress * 100).toStringAsFixed(0)}%',
                style: TextStyle(
                  fontSize: 10,
                  color: color,
                ),
              ),
          ],
        ),
      ),
    );
  }
}